package com.toocms.jinjuhang.ui.mine.integral

import android.app.Application
import androidx.databinding.ObservableArrayList
import androidx.databinding.ObservableField
import com.toocms.jinjuhang.R
import com.toocms.jinjuhang.BR
import com.toocms.jinjuhang.config.Urls
import com.toocms.jinjuhang.config.UserRepository
import com.toocms.jinjuhang.data.User
import com.toocms.jinjuhang.data.center.PointsRecordsData
import com.toocms.jinjuhang.data.system.PointsNoticeData
import com.toocms.jinjuhang.widget.view_model.requestData
import com.toocms.tab.base.BaseModel
import com.toocms.tab.base.BaseViewModel
import com.toocms.tab.binding.ItemBinding
import com.toocms.tab.binding.command.BindingAction
import com.toocms.tab.binding.command.BindingCommand
import com.toocms.tab.bus.event.SingleLiveEvent

class MyIntegralModel(application: Application) : BaseViewModel<BaseModel>(application) {

    private var p = 1
    val dataObservableField = ObservableField<User>()
    val noticeObservableField = ObservableField<String>()

    val items = ObservableArrayList<MyIntegralRecordItemModel>()
    val itemBinding = ItemBinding.of<MyIntegralRecordItemModel>(
        BR.myIntegralRecordItemModel, R.layout.item_my_integral_record
    )

    val stopRefreshOrLoadSingleLiveEvent = SingleLiveEvent<Unit>()

    val refreshBindingCommand = BindingCommand<BindingAction>(BindingAction {
        refreshRecords()
    })

    val loadBindingCommand = BindingCommand<BindingAction>(BindingAction {
        loadRecords()
    })


    init {
        memberInfo(true)
        requestData(Urls.System.POINTS_NOTICE,
            resultClass = PointsNoticeData::class.java,
            result = {
                noticeObservableField.set(it.notice)
            })
        refreshRecords()
    }

    private fun refreshRecords() {
        p = 1
        pointsRecords(p)
    }

    private fun loadRecords() {
        p++
        pointsRecords(p)
    }

    private fun memberInfo(isShowLoading: Boolean = false) {
        val params = mutableMapOf<String, String?>()
        params["member_id"] = UserRepository.user.member_id
        requestData(Urls.Center.MEMBER_INFO,
            params,
            resultClass = User::class.java,
            isShowLoading = isShowLoading,
            result = {
                dataObservableField.set(it)
            })
    }

    private fun pointsRecords(p: Int) {
        val params = mutableMapOf<String, String?>()
        params["member_id"] = UserRepository.user.member_id
        params["p"] = p.toString()
        requestData(Urls.Center.POINTS_RECORDS,
            params,
            resultClass = PointsRecordsData::class.java,
            result = {
                if (1 == p) items.clear()
                it.list?.forEach {
                    items += MyIntegralRecordItemModel(this, ObservableField(it))
                }
            },
            finish = {
                stopRefreshOrLoadSingleLiveEvent.call()
            })
    }

}